/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.wdb.servlet;

import org.vacoor.nothing.common.misc.util.Characters;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

/**
 */
public class WdbServlet extends ResourceServlet {
    private GroovyShellServlet groovyShell;
    private DatabaseServlet dbServlet;

    public WdbServlet() {
        super("support/web");
        groovyShell = new GroovyShellServlet();
        dbServlet = new DatabaseServlet();
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        groovyShell.init(config);
        dbServlet.init(config);
    }

    @Override
    protected void handleRequest(String path, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        path = path.endsWith("/") ? path.substring(0, path.length() - 1) : path;

        if ("/gsh".equals(path)) {
            groovyShell.service(request, response);
            return;
        }

        if ("/database/execute".equals(path)) {
            String result = "";
            try {
                Connection conn = dbServlet.getConnection(request, response);

                if (conn == null) {
                    response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "No Connection");
                    return;
                }

                result = dbServlet.executeSql(conn, request.getParameter(DatabaseServlet.SQL_PARAM_NAME));
            } catch (SQLException e) {
                result = ("{" + "\"count\": " + -1 + ", \"msg\":" + Characters.toUnicode(e.getMessage()) + "}");
            }
            response.getWriter().write(result);
            return;
        }

        response.sendError(404);
    }
}
